package com.example.control;


import com.example.domain.t_article;
import com.example.domain.t_comment;
import com.example.domain.t_user;
import com.example.model.responseData.StaticticsBo;
import com.example.model.responseData.articleResponseData;
import com.example.service.IArticleService;
import com.example.service.ISiteService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageReader;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;

//后台管理
@Controller
@RequestMapping("/admin")
public class AdminController {
    private static final Logger logger= (Logger) LoggerFactory.getLogger(CommentControl.class);

    @Value("${file.upload}")
    private String path;
    @Autowired
    private IArticleService art;
    @Autowired
    private ISiteService site;

    //管理中心index
    @RequestMapping(value = {"/","","/index"})
    public String index(HttpServletRequest request){
        t_user loginUser = (t_user)request.getSession().getAttribute("loginUser");
        if(loginUser==null){
            logger.error("异常访问,未登录用户");
            return "login?url="+String.valueOf(request.getRequestURL());
        }
        String avatar = loginUser.getAvatar();

        //获取最新博客以及统计数据
        List<t_article> arts = site.recentArticles(5,loginUser.getId());
        List<t_comment> coms = site.recentComents(5,loginUser.getId());
        StaticticsBo bo = site.getStatistic(loginUser.getId());
        //返回数据
        request.setAttribute("articles",arts);
        request.setAttribute("comments",coms);
        request.setAttribute("statistics",bo);
        return "back/index";
    }

    //发表文章,返回新建文章模板页面
    @RequestMapping(value={"/article/toEditPage"})
    public String newArticle(HttpServletRequest request){
        t_user loginUser = (t_user)request.getSession().getAttribute("loginUser");
        List<String> categories = art.getCategories(loginUser.getId());
        request.setAttribute("categoriesList",categories);

        return "back/article_edit";
    }
    //对写好的文章提交处理保存。
    @PostMapping("/article/publish")
    @ResponseBody
    public articleResponseData publishArticle(HttpServletRequest req,
                                              int allow_comment,String categories,
                                              String content,String title,String tags,
                                              @RequestParam(defaultValue = "false") boolean secret){
        t_article article = new t_article();
        article.setTitle(title);article.setContent(content);
        article.setCategories(categories);
        article.setSecret(secret);
        article.setTags(tags);article.setAllow_comment(allow_comment);
        t_user loginUser = (t_user)req.getSession().getAttribute("loginUser");
        if(loginUser==null){
            logger.error("发表失败,未登录用户");
            return articleResponseData.fail("用户未登录");
        }
        article.setUser_id(loginUser.getId());
        if(article.getCategories()==null||StringUtils.isBlank(article.getCategories())){
            article.setCategories("默认分类");
        }
        try{
            art.save(article);
            logger.info("文章发表成功:"+article.getContent().length());
            return articleResponseData.ok();
        }catch (Exception e){
            logger.error("发表失败："+e.getMessage());
            return articleResponseData.fail();
        }
    }
    //跳转到后台的列表页面
    @GetMapping("/article")
    public String index(@RequestParam(value = "page",defaultValue = "1") int count,
                        @RequestParam(value = "count",defaultValue = "10") int size,
                        @RequestParam(value = "cate",defaultValue = "") String cate,
                        @RequestParam(value = "tags",defaultValue = "") String tags,
                        HttpServletRequest request){
        //System.out.println(count+","+size);
        t_user loginUser = (t_user)request.getSession().getAttribute("loginUser");

        //封装要进行的分类查找
        t_article likeArt = new t_article();
        if(tags!=null&&!tags.equals("")) {
            tags=tags.replace(" ","");
            likeArt.setTags(tags);
        }
        if(cate!=null&&!cate.equals("")) {
            cate=cate.replace(" ","");
            likeArt.setCategories(cate);
        }
        likeArt.setUser_id(loginUser.getId());
        likeArt.setUsername(loginUser.getUsername());
        //得到所有的标签
        Set<String> tagslist= new HashSet<String>();
        List<t_article> t_articles = art.selectList(loginUser.getId());
        for(t_article t:t_articles){
            if(t.getTags()==null||"".equals(t.getTags()))continue;
            String[] split = t.getTags().split(",");
            //System.out.println(split.length);

            tagslist.addAll(Arrays.asList(split));
        }
        tagslist.remove("");
        tagslist.remove(" ");
        request.setAttribute("tagsList",tagslist);
        //System.out.println(tagslist);
        //按照article详细分类
        request.setAttribute("cate",cate);
        List<String> categories = art.getCategories(loginUser.getId());
        request.setAttribute("categoriesList",categories);
        PageInfo<t_article> lis = art.getPage(count,size,likeArt);
        request.setAttribute("articles",lis);
        return "back/article_list";
    }

    //删除文章
    @PostMapping(value = "/article/delete")
    @ResponseBody
    public articleResponseData deleteArticle(@RequestParam int id){
        try{
            art.deleteById(id);
            logger.info("文章article（id="+id+"）删除成功");
            return articleResponseData.ok();
        }catch (Exception e){
            logger.error("文章：id="+id+"删除失败,错误信息："+e.getMessage());
            return articleResponseData.fail();
        }
    }

    //修改文章
    //跳转修改页面
    @GetMapping("/article/{id}")
    public String editArticle(@PathVariable("id") String id,HttpServletRequest req){
        t_user loginUser = (t_user)req.getSession().getAttribute("loginUser");
        List<String> categories = art.getCategories(loginUser.getId());
        req.setAttribute("categoriesList",categories);
        t_article article = art.selectById(Integer.parseInt(id));
        req.setAttribute("contents",article);
        req.setAttribute("categories",article.getCategories());//文章分类
        return "back/article_edit";
    }
    //文章修改保存
    @RequestMapping("/article/modify")
    @ResponseBody
    public articleResponseData modifiyArticle(t_article article){
        try{
            art.updateById(article);
            logger.info("文章（article：id="+article.getId()+"）更新成功");
            return articleResponseData.ok();
        }catch (Exception e){
            logger.error("文章更新错误，错误信息："+e.getMessage());
            return articleResponseData.fail();
        }
    }
    //上传文章中图片保存
    @PostMapping("/article/uploadImage")
    @ResponseBody
    public String uploadImage(MultipartFile mdImage, HttpServletRequest request){
        HttpSession session = request.getSession();
        t_user loginUser = (t_user) session.getAttribute("loginUser");
        if(loginUser==null)return null;

        String filename = mdImage.getOriginalFilename(); //获取上传的文件名
        //随机数+生成文件名生成新的文件名
        filename = UUID.randomUUID()+"_"+filename;

        String dirPath=System.getProperty("user.dir")+path+loginUser.getId()+"/";
        File file1 = new File(dirPath);
        if(!file1.exists()){
            file1.mkdirs();
        }
        try{
            //文件转存
            mdImage.transferTo(new File(dirPath+filename));
            logger.info("用户："+loginUser.getUsername()+",上传了图片："+dirPath+filename+"上传成功");
        }catch (Exception e){
            //上传失败，覆盖反馈结果
            //e.printStackTrace();
            logger.error("上传图片失败: "+e.getMessage());
        }
        String root = String.valueOf(request.getRequestURL());
        String replace = root.replace(request.getRequestURI(), "");
        return request.getContextPath()+"/article/image/"+loginUser.getId()+"/"+filename;
    }
}
